<?php
error_reporting(E_STRICT | E_ALL);
date_default_timezone_set('America/New_York');
ini_set('display_errors', 1);
set_time_limit(60*60);
ini_set('memory_limit', '512M');

$g_start = microtime(true);

require_once "config.php";

$dailyPlays = array();
chdir(RAW_DATA_ROOT);
//loop every month
foreach (glob("*_*") as $dirname) {
	if (is_dir($dirname)) {
		chdir(RAW_DATA_ROOT . '/' . $dirname);
		
		//loop every day in this month
		for ($i=1; $i<32; $i++) {
			$date = sprintf("%02d", $i);
			$lalalootDailyPlayed = 0;
			$cashdazzleDailyPlayed = 0;
			$users = array();
			
			//loop every hour in this day
			foreach (glob($date . "_*") as $filename) {
				if (count(explode('_', $filename)) == 2) {
					$handler = fopen(RAW_DATA_ROOT . '/' . $dirname . '/' . $filename, 'r');
					if ($handler) {
						
						while (!feof($handler)) {
							$line = fgets($handler);
							if (!empty($line)) {
								$args = explode(':', $line);
								if (!empty($args[4]) && !empty($args[11]) && !empty($args[3]))
								{
									$event = $args[4];
									$site = $args[11];
									if ($event == 'played') {
										if (in_array($args[3], $users) === false) {
											if ($site == 'lalaloot.com') {
												$lalalootDailyPlayed += 1;
												$users[] = $args[3];
											} elseif ($site == 'cashdazzle.com') {
												$cashdazzleDailyPlayed += 1;
												$users[] = $args[3];
											}
										}
									}
								}
							}
						}
						fclose($handler);
					}
				}
			}
			$dailyPlays[$dirname][$date] = array('lalaloot.com'=>$lalalootDailyPlayed, 'cashdazzle.com'=>$cashdazzleDailyPlayed);
		}
		chdir(RAW_DATA_ROOT);
	}
}
//var_dump($dailyPlays);

/*
$temp = '';
foreach ($dailyPlays as $ymonth => $play) {
	$temp .= "Year-Month: $ymonth\n";
	foreach ($play as $date => $dailyPlayed) {
		if ($dailyPlayed['lalaloot.com'] != 0 || $dailyPlayed['cashdazzle.com'] != 0) {
			$temp .= "\t" . $date . "\n"; 
			$temp .= "\t\tLalaloot:" . $dailyPlayed['lalaloot.com'] . "\n";
			$temp .= "\t\tCashdazzle:" . $dailyPlayed['cashdazzle.com'] . "\n";
		}
		
	}
	$temp .= "\n\n";
}
*/

$handle = fopen(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'DAU', 'w+') or die('error');
foreach ($dailyPlays as $ymonth => $play)
{
	foreach ($play as $date=>$dailyPlayed)
	{
		if ($dailyPlayed['lalaloot.com'] != 0 || $dailyPlayed['cashdazzle.com'] != 0)
		{
			$row = $ymonth . "-" . $date . "\t" . $dailyPlayed['cashdazzle.com'] . "\t" . $dailyPlayed['lalaloot.com'] . "\n";
			fwrite($handle, $row);
		}
	}
}
fclose($handle);
//fwrite($handle, $temp);

echo 'Totally: '. (microtime(true) - $g_start) . " seconds \n";
echo "memory: " . memory_get_peak_usage() . " bytes \n";
